package JasPerl::JSTL::Fmt::CLDR;

use 5.010;
use strict;
use warnings;

use Module::Load::Conditional qw(can_load);

sub root {
    return $_[0]->get_locale('root');
}

sub get_locale {
    my ($class, $id) = @_;
    $id = 'root' unless length $id;
    my $module = join('::', __PACKAGE__, split(/[_-]/, $id));
    if (can_load( modules => { $module => undef } )) {
        return $module;
    } else {
        die "Cannot load $module";
    }
}

sub id {
    my $self = shift;
    return join('_', $self->language, $self->territory, $self->variant);
}

sub parent {
    my $self = shift;
    if (defined $self->variant) {
        return $self->get_locale($self->language . '_' . $self->territory);
    } elsif (defined $self->territory) {
        return $self->get_locale($self->language);
    } elsif ($self->language ne 'root') {
        return $self->get_locale('root');
    } else {
        return;
    }
}

sub language {
    return $_[0]->CLDR->{identity}->{language};
}

sub territory {
    return $_[0]->CLDR->{identity}->{territory};
}

sub variant {
    return $_[0]->CLDR->{identity}->{variant};
}

sub find_node {
    my ($self, $path) = @_;
    warn "$self $path";

    my $node = $self->CLDR;
    foreach (split('/', $path)) {
        if (exists $node->{$_}) {
            $node = $node->{$_}
        } elsif (my $parent = $self->parent) {
            return $parent->find_node($path);
        } else {
            return;
        }
    }
    return $node;
}

1;
